<template>
  <div class="search-con">
    <div class="s-box">
      <p class="sb-tit">企业画像</p>
      <div class="search-box">
        <el-autocomplete
          class="search-bar-inp"
          popper-class="complete-list"
          v-model="searchText"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入公司相关信息进行查询"
          placement="bottom"
          :debounce="300"
          :popper-append-to-body="false"
          :trigger-on-focus="false"
          @select="search"
          @keyup.enter.native="search"
        ></el-autocomplete>
        <el-button type="primary" @click="search" class="search-button"
          >搜索</el-button
        >
      </div>
      <!-- 热搜 -->
      <p class="hot-search">
        热搜：
        <span
          v-for="(item, index) in hotSearchList"
          :key="index"
          @click="toHotCompany(item.fullName)"
          >{{ item.shortName }}</span
        >
      </p>
    </div>
    <!-- 数据进度 -->
    <el-dialog
      title="数据生成进度"
      :visible.sync="dialogProgress"
      :before-close="closeTypes"
      width="45%"
      class="eldialog"
    >
      <el-progress class="elprogress" :percentage="percent"></el-progress>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeTypes">后台处理</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { Loading } from "element-ui";
let types = null;

export default {
  data() {
    return {
      //
      searchText: "",
      cancel2: null,
      hotSearchList: [
        {
          shortName: "三生国健",
          fullName: "三生国健药业（上海）股份有限公司",
        },
        {
          shortName: "旷视科技",
          fullName: "北京旷视科技有限公司",
        },
        {
          shortName: "观致汽车",
          fullName: "观致汽车",
        },
        {
          shortName: "大立科技",
          fullName: "浙江大立科技股份有限公司",
        },
      ],
      percent: 0,
      dialogProgress: false,
      hotLoading: null,
      cancel3: null,
    };
  },
  created() {
    //
  },
  methods: {
    // 查询补全
    querySearchAsync(queryString, cb) {
      if (this.cancel2 !== null) {
        this.cancel2();
      }
      if (this.searchText === "") {
        cb([]);
        return;
      }
      let ths = this;
      this.querySearchList = [];
      this.$get(
        this.$Url.comparison.autoComplete,
        {
          keyWord: queryString || this.searchText,
        },
        new axios.CancelToken(function executor(c) {
          ths.cancel2 = c;
        })
      ).then((res) => {
        let list = res.data ? res.data.result : [];
        list.forEach((v) => {
          this.querySearchList.push({ value: v._source.name });
        });
        cb(this.querySearchList);
      });
    },
    search() {
      // this.$cookie.set("companyName", "浙江大立科技股份有限公司");
      // this.$router.push({
      //   name: "technologyOverview",
      // });
      // return;
      // 公司
      if (this.$cookie.get("token") && this.$cookie.get("token") !== "") {
        if (this.searchText !== "") {
          // console.log("searchText", this.searchText);
          this.$cookie.set("companyName", this.searchText);
          this.$router.push({
            // name: "searchList",
            // query: {
            //   companyName: this.searchText,
            // },
            name: "EISearchResult",
            query: {
              keyword: this.searchText,
              ipi: 1,
            },
          });
        } else {
          this.$message.warning("请输入查询内容！");
        }
      } else {
        this.$message.warning("请登录后进行查询！");
      }
    },
    // 热搜
    toHotCompany(item) {
      let ths = this;
      if (this.cancel3 !== null) {
        this.cancel3();
      }

      this.hotLoading = Loading.service({
        lock: true,
        text: "加载中。。。",
        spinner: "el-icon-loading",
        background: "rgba(0,0,0,0.6)",
      });

      this.$get(
        this.$Url.comparison.autoComplete,
        {
          keyWord: item,
        },
        new axios.CancelToken(function executor(c) {
          ths.cancel3 = c;
        })
      )
        .then((res) => {
          let list = res.data ? res.data.result : [];
          if (list.length > 0) {
            this.enterDetails(list[0]);
            return;
          }
          this.hotLoading.close();
        })
        .catch((err) => {});
    },
    // 进入热搜企业
    enterDetails(item, isNeedCheck) {
      localStorage.setItem("eid", item._id);
      types = null;
      let checkUrl = this.$Url.search.check;
      if (!isNeedCheck) {
        checkUrl = this.$Url.search.check2;
      }
      let ths = this;
      this.$get(
        checkUrl,
        {
          companyName: item._source.name,
          eid: item._id,
        },
        new axios.CancelToken(function executor(c) {
          ths.cancel3 = c;
        })
      ).then((res) => {
        this.hotLoading.close();
        // 无访问权限
        if (res.status === 40305) {
          return;
        }
        // 默认重置公司是否有专利的cookie
        this.$cookie.set("isHavePatent", true);
        // 清除公司国别的cookie
        this.$cookie.remove("companyCountry");

        let promise = new Promise((resolve, reject) => {
          // 获取公司国别
          this.$get(this.$Url.company.country, {
            // companyname: item._source.name
            eid: item._id,
          }).then((data) => {
            this.$cookie.set("companyCountry", data.data);
            resolve("next");
          });
        });
        promise.then(() => {
          if (res.status === 40401) {
            // 获取新闻信息
            this.$post(this.$Url.news.getData, {
              name: item._source.name,
            }).then((data) => {});

            this.$cookie.set("companyName", item._source.name);
            this.$cookie.set("isHavePatent", false);
            this.addHistory(item);
            this.$router.push({
              name: "technologyOverview",
            });
            return;
          }

          if (res.data.type == 0) {
            // 获取新闻信息
            this.$post(this.$Url.news.getData, {
              name: item._source.name,
            }).then((data) => {});

            this.$cookie.set("companyName", item._source.name);
            this.addHistory(item);
            this.$router.push({
              name: "technologyOverview",
            });
            if (types != null) {
              clearTimeout(types);
              types = null;
            }
          } else if (res.data.type == 1) {
            this.$confirm("后台生成数据需要一定的时间", "是否继续？", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              // 获取新闻信息
              this.$post(this.$Url.news.getData, {
                name: item._source.name,
              }).then((data) => {});

              this.$get(this.$Url.search.generateData, {
                companyname: item._source.name,
                jueduidefen: true,
                eid: item._id,
              }).then((res) => {
                if (res.status == 205) {
                  this.$message.warning(res.message);
                }
                this.addHistory(item);
              });
            });
          } else if (res.data.type == 2) {
            this.dialogProgress = true;
            this.percent = Number(res.data.percent) || 0;
            types = setTimeout(() => {
              this.enterDetails(item, false);
            }, 4000);
          } else if (res.data.type == 3) {
            this.closeTypes();
            this.$message.error("数据计算失败，请联系后台管理员");
          }
        });
      });
    },
    closeTypes() {
      this.dialogProgress = false;
      clearTimeout(types);
      types = null;
      // 中止请求
      this.cancel3();
      this.dialogProgress = false;
    },
    // 添加浏览历史
    addHistory(item) {
      let obj = {
        companyName: item._source.name,
        eid: item._id,
      };
      this.$post(this.$Url.history.addHistory, {
        sq: JSON.stringify(obj),
      }).then((res) => {});
    },
  },
};
</script>
<style lang="scss">
.el-message-box{
  .el-button--primary {
    color: #FFF;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button--primary:active,.el-button--primary:focus,.el-button--primary:hover{
  color: #FFF !important;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button:focus, .el-button:hover {
    color: $mainColor;
    border-color: $mainColor;
    background-color: $hoverColor;
}
}
</style>
<style lang="scss" scoped>
.search-con {
  height: calc(100vh - 0.7rem);
  background-color: $color45;
}
.s-box {
  width: 50%;
  margin: 0 auto;
  position: relative;
  z-index: 2;
  padding: 40px 0;
  color: #fff;

  .sb-tit {
    margin-bottom: 40px;
    font-size: 24px;
    text-align: center;
  }
  .search-box {
    display: flex;
    .search-bar-inp {
      width: 100%;
      border: 0;
      font-size: 16px;
    }
    .search-button {
      margin-left: 0.14rem;
    }
  }

  .hot-search {
    position: relative;
    padding-top: 10px;
    font-size: 12px;
    font-weight: bold;
    color: $mainColor;
    span {
      margin-right: 10px;
      color: $mainColor;
      cursor: pointer;
      &:hover {
        color: #fff;
      }
    }
  }
}
</style>
